<?php

namespace app\admin\controller\course;

use addons\epay\library\Service;
use app\common\controller\Backend;
use app\common\model\User;
use Yansongda\Pay\Pay;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\course\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['User','Course'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function shenhe($ids=null){
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if(!$id){
            $list = Db::name("course_order")->alias('r')
                ->field("r.*,u.nickname,c.name as course_name,m.name as merchant_name")
                ->join("user u",'r.user_id = u.id', 'LEFT')
                ->join("course c",'r.course_id = c.id', 'LEFT')
                ->join("merchant m",'r.merchant_user_id = m.id', 'LEFT')
                ->where(['r.id'=>$ids])
                ->find();
            $pay_type_text = $list['pay_type'] == 1?'现金支付':'积分支付';
            $list['pay_type_text'] = $pay_type_text;
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            return $this->view->fetch();
        }
        // exit;
        $order_data = Db::name("course_order")->where(['id'=>$id])->find();
        if(!$order_data){
            $this->error("数据有误");
        }
        if($status == 1){
            Db::name("course_order")->where(['id'=>$id])->update(['status'=>1]);
            Db::name("user_recharge_card")->where(['order_id'=>$id])->update(["status"=>1]);
        }else{
            if($order_data['pay_type'] == 1){
                $paytype = 'wechat';
                $config = Service::getConfig($paytype);
                $response = Pay::wechat($config)->refund([
                    'type'          => 'miniapp',
                    'out_trade_no'  => $order_data['out_trade_no'],
                    'out_refund_no' => time(),
                    'total_fee'     => $order_data['pay_money'] * 100,
                    'refund_fee'    => $order_data['pay_money'] * 100
                ]);
                if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                    throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
                }
            }else {
                $score = Db::name("user_score_log")->where(['order_id' => $id, 'is_fixed' => 0])->value("score");
                $fixed_score = Db::name("user_score_log")->where(['order_id' => $id, 'is_fixed' => 1])->value("score");
                if ($score) {
                    User::score(abs($score), $order_data['user_id'], '退款', 0, $order_data['merchant_user_id'], $id);
                }
                if($fixed_score){
                    $fixed_score_day = Db::name("config")->where(['name'=>'fixed_score_day'])->value('value');
                    $end_time = strtotime($fixed_score_day." day");
                    User::score(abs($fixed_score), $order_data['user_id'], '退款', 1, $order_data['merchant_user_id'], $id,$end_time);
                }

            }
            Db::name("course_order")->where(['id' => $id])->update(['status' => 4]);
            Db::name("user_recharge_card")->where(['order_id' => $id])->delete();
        }
        $this->success("操作成功");
    }
}
